﻿using System;
using System.Collections.Generic;
using System.Linq;
using Medianamik.Core;
using System.Web.UI.WebControls;

namespace Medianamik.UI.Controls
{
    public class ManyToOneCheckboxList : BaseMedianamikControl
    {
        private readonly CheckBoxList _chkList = new CheckBoxList { ID = ControlToValidateId };

        public override object GetValue()
        {
            EnsureChildControls();

            return string.Join(",",
                _chkList.Items.Cast<ListItem>()
                .Where(i => i.Selected)
                .Select(i => i.Value)
                .ToArray());
        }

        public override Type TypeOfValue
        {
            get { return typeof(string); }
        }

        protected override void CreateControlHierarchy(bool pUseDataSource)
        {
            Controls.Add(_chkList);

            if (pUseDataSource)
            {
                var selectedValues = Enumerable.Empty<string>();
                if(DataSource is string && !string.IsNullOrEmpty((string)DataSource))
                {
                    var data = (string) DataSource;
                    selectedValues = data.Split(',');
                }

                if(RepeatColumns.HasValue)
                    _chkList.RepeatColumns = RepeatColumns.Value;

                if (Options.Count > 0)
                {
                    //La propriété est normalement identique pour toutes les options.
                    var propertyId = Options[0].PropertyId;
                    var optionNodes = NodeManager.GetNodes(Options.Select(o => o.NodeId).ToArray())
                        .OrderBy(n => n.Name);
                    
                    foreach (var node in optionNodes.Where(n => !ControlInfo.TreeRootNodeID.HasValue || 
                                n.IsChildOf(ControlInfo.TreeRootNodeID.Value)))
                    {
                        ListItem item = BuildItems(node, propertyId);
                        _chkList.Items.Add(item);
                        item.Selected = selectedValues.Any(v => v.Equals(node.ID.ToString()));
                    }
                }
            }
        }

        protected virtual ListItem BuildItems(Node node, Guid propertyId)
        {
            return new ListItem(node.DefaultInstance[propertyId].GetValue<string>(), 
                                node.ID.ToString());
        }

        protected virtual int? RepeatColumns
        {
            get { return null; }
        }

        public override void SetValue(object value)
        {
            EnsureChildControls();
            _chkList.SelectedValue = (string)value;
        }
    }
}